package com.app.bimo.module_bookrack.mvp.persenter;



import com.app.bimo.commonbusiness.mvp.BasePresenter;
import com.app.bimo.commonbusiness.network.RxObservableUtil;
import com.app.bimo.commonbusiness.util.DeleteUtil;
import com.app.bimo.commonbusiness.util.FileUtils;
import com.app.bimo.library_db.BookData;
import com.app.bimo.library_db.UserData;
import com.app.bimo.library_db.helper.ChapterHelper;
import com.app.bimo.library_db.helper.UserHelper;
import com.app.bimo.module_bookrack.mvp.constract.BookrackReadRecordContract;

import java.io.File;


public class BookrackReadRecordPresenter extends BasePresenter<BookrackReadRecordContract.Model, BookrackReadRecordContract.View> {
    public BookrackReadRecordPresenter(BookrackReadRecordContract.Model model, BookrackReadRecordContract.View rootView) {
        super(model, rootView);
    }


    public void requestFromModel(int page) {
        RxObservableUtil.subscribe(
                mModel.getBooks(page + "")
                , bindCustomLifecycle(true), bookStoreDataList -> {
                    /**
                     * 断网后点击重试  需要dialog  获取数据成功后 消失
                     */
                    mRootView.hideDialogLoading();
                    // 处理数据 直接获取到List<JavaBean> carBeans
                    if (page == 1 && bookStoreDataList.size() == 0) {
                        mRootView.showEmpty();
                    } else {
                        mRootView.readRecordNotify(bookStoreDataList);
                    }
                });

    }

    /**
     * 删除阅读足迹
     */
    public void requestFromDel(BookData data) {
        String novelid="";
        if (data != null) {
            novelid = data.getNovelid();
        }


        //删除本地阅读足迹文件（缓存）
        String uuid = "";
        UserData userData = UserHelper.getsInstance().findUser();
        if (userData != null) {
            uuid = userData.getUuid();
            File file = null;
            if (data != null){
                file = new File(FileUtils.getBookCachePath(mRootView.getMContext()) + uuid
                        + File.separator + data.getNovelid());
            }else{
                file = new File(FileUtils.getBookCachePath(mRootView.getMContext()) + uuid
                        + File.separator);
            }

            DeleteUtil deleteUtil = new DeleteUtil();
            deleteUtil.delete(file.getAbsolutePath());
        }

        //数据库中删除本书记录（阅读位置）
        if (data != null){
            ChapterHelper.getInstance().deleteBookRecord(data.getNovelid(),uuid);
        }else{
            ChapterHelper.getInstance().deleteBookRecord(null,uuid);
        }

        RxObservableUtil.subscribe(
                mModel.delBooks(novelid)
                , bindCustomLoadingLifecycle(true), bookStoreDataList -> {
                    // 处理数据 直接获取到List<JavaBean> carBeans
                    mRootView.delNotify(data);
                });


    }
}
